﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Agro.Library;
using SN.Core;
using Ninject;
using Agro.Services;
using SN.Data;
using Agro.Models;
using System.IO;
using System.Web.Security;

namespace Agro.Web.Areas.SystemManage.Controllers
{
    public class MessageController : BaseController
    {
        [Inject]
        public IMessageService MessageService { get; set; }

        public ActionResult MessageList()
        {
            ViewBag.Organization_Id = CurrUser.UserInfo.User_OrganizationID;
            return View();
        }
        [HttpPost]
        public ActionResult GetMessageList(string id, string messagetype, QueryBase query)
        {
            WhereClip where = WhereClip.All;
            if (id != null)
                switch (messagetype)
                {
                    case "receive":
                        where = T_Message._.Message_ReceiveOrgid == id;
                        break;
                    default:
                        where = T_Message._.Message_SendOrgid == id;
                        break;

                }

            var list = MessageService.GetMessageList(query, where);
            return JqGrid(list, query);
        }


        //发送消息
        public ActionResult SendMessage(string id)
        {
            T_Message Message;
            if (string.IsNullOrEmpty(id))
            {
                Message = new T_Message();
                ViewBag.MessageType = "add";
                ViewBag.SendOrgName=MessageService.GetOrganizationName(CurrUser.UserInfo.User_OrganizationID.ToString()) ;
                ViewBag.CreateUserName = CurrUser.UserInfo.User_Name;
            }
            else
            {
                Message = MessageService.GetEntity<T_Message>(T_Message._.Message_ID == id);
                //打开消息的同时，将消息的阅读状态修改为已读
                MessageService.UpdateMessageStatus(id, CurrUser);
                ViewBag.MessageType = "read";
                ViewBag.SendOrgName = MessageService.GetOrganizationName(Message.Message_SendOrgid.ToString());
                ViewBag.CreateUserName =  MessageService.GetEntity<T_User>(T_User._.User_ID==Message.Message_CreateUserid).User_Name.ToString() ;

            }
            //显示接收单位的名称
            if (Message.Message_ReceiveOrgid > 0)
                ViewBag.ReceiveOrgName = MessageService.GetOrganizationName(Message.Message_ReceiveOrgid.ToString());

            ViewBag.auth = Request.Cookies[FormsAuthentication.FormsCookieName] == null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value;
            ViewBag.GUID = Guid.NewGuid().ToString().Replace("-", "");
            //不传送Message.AttachmentFile,因为是二进制文件，可能很大，影响页面打开速度。
            Message.Message_AttachmentFile = null;
            return View(Message);
        }

        [HttpPost]
        public ActionResult MessageSave(HttpPostedFileBase FileData, string GUID, string Message_Id, FormCollection collection)
        {
            string Msg = string.Empty;
            string ReceiveOrgid = collection["Message_ReceiveOrgid"].ToString();
            string title = collection["Message_Title"].ToString();
            string Contents = collection["Message_Content"].ToString();
            byte[] bytes = null;
            string fileName = string.Empty;
            string[] ArrayOrgid = ReceiveOrgid.Split(',');

            ///////////////////////////////////////////////处理附件
            if (!string.IsNullOrEmpty(GUID))
            {

                fileName = Path.GetFileName(FileData.FileName);
                int FileLen;
                FileLen = FileData.ContentLength;
                bytes = new byte[FileLen];
                FileData.InputStream.Read(bytes, 0, FileLen);

            }
            //////////////////////////////////////////////////////////////////

            T_Message Message;
            for (int i = 0; i < ArrayOrgid.Length; i++)
            {
                Message = new T_Message();
                Message.Message_ReceiveOrgid = Convert.ToInt32(ArrayOrgid[i]);
                Message.Message_Title = title;
                Message.Message_Content = Contents;
                Message.Message_AttachmentName = fileName;
                Message.Message_AttachmentFile = bytes;
                //保存
                MessageService.SaveMessage(Message, out Msg, CurrUser);
            }
            if (string.IsNullOrEmpty(Msg))
            {
                return SNJson("1", Msg);
            }
            else
            {
                return SNJson("", Msg);
            }
            //string returnstr = "[{'filename':'" + fileName + "','savefilename':'" + saveName + "','fileExtension':'" + fileExtension.Replace(".", "") + "'}]";
            //return Content(returnstr);
        }


        [HttpPost]
        public ActionResult MessageDelete(string ids)
        {
            string msg = string.Empty;
            MessageService.DeleteMessage(ids, out msg);
            return SNJson(msg);
        }

        public void DownLoadFile(string id)
        {
            string msg = string.Empty;

            T_Message Message = new T_Message();
            Response.Clear();
            if (string.IsNullOrWhiteSpace(id))
            {
                msg = "请选择要下载的文件！";
                Response.Write("<script>alert('提示:" + msg + "');</script>");
                Response.End();
                return;
            }
            //必须是收信人或发信人才能下载附件
            Message = MessageService.GetEntity<T_Message>(T_Message._.Message_ID == id && WhereClip.Bracket(T_Message._.Message_ReceiveOrgid == CurrUser.UserInfo.User_OrganizationID || T_Message._.Message_SendOrgid == CurrUser.UserInfo.User_OrganizationID));

            //处理下载
            Response.Clear();
            string filePath = Message.Message_AttachmentName;
            if (Message.Message_AttachmentFile == null)
            {
                msg = "所要下载的文件不存在！";
                Response.Write("<script>alert('提示:" + msg + "');</script>");
                Response.End();
                return;
            }
            Response.ContentType = "application/octet-stream";
            //通知浏览器下载文件而不是打开
            //Content-Disposition参数：
            //attachment --- 作为附件下载    
            //inline --- 在线打开
            Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filePath, System.Text.Encoding.UTF8));

            Response.BinaryWrite(Message.Message_AttachmentFile);
            Response.Flush();
            Response.End();


        }
    }
}
